/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package Controller;

import Entity.FileTA;
import Entity.User;
import Model.FileTAModel;
import java.io.*;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Iterator;
import java.util.List;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;



/**
 *
 * @author mr2
 */
public class FileTALogic{
    HttpServletRequest request;
    HttpServletResponse response;

    public FileTALogic(HttpServletRequest request, HttpServletResponse response) {
        this.request = request;
        this.response = response;
    }
    
    public String KelolaFileTA(){
        
        HttpSession session = request.getSession();
        ArrayList ListRole = new ArrayList();
        ListRole = (ArrayList) session.getAttribute("role");
        
        boolean bukanRole = true;
        if (session.getAttribute("role") != null) {
            for (int i = 0; i < ListRole.size(); i++) {
                if ((ListRole.get(i).equals("koordinator_ta"))) {
                    bukanRole = false;
                }
            }
        }
        
        if (session.getAttribute("role") == null) {
            return "login";
        } else if (bukanRole) {
            request.setAttribute("menu", "monitoringTA");
            request.setAttribute("submenu", "");
            return "AccessDenied";
        }else {
            
            String namaFile = request.getParameter("namaFile");
            String pesan = request.getParameter("pesan");
            FileTAModel file = new FileTAModel(); 
            List<FileTA> listFile = file.ListFile();

            request.setAttribute("namaFile", namaFile);
            request.setAttribute("pesan", pesan);
            request.setAttribute("listFile", listFile);

            request.setAttribute("menu", "monitoringTA");
            request.setAttribute("submenu", "kelolaFileTA");

            return "monta/KoorTA_table_kelola_file_ta.jsp";
        }
    }
    
    public String ListFileTA(){
            
        String namaFile = request.getParameter("namaFile");
        String pesan = request.getParameter("pesan");
        FileTAModel file = new FileTAModel(); 
        List<FileTA> listFile = file.ListFile();
        
        request.setAttribute("namaFile", namaFile);
        request.setAttribute("pesan", pesan);
        request.setAttribute("listFile", listFile);
        request.setAttribute("menu", "monitoringTA");
        request.setAttribute("submenu", "fileTA");
            
        return "monta/ListFileTA.jsp";
    }
    
    public String UploadFileTA(){
            
            HttpSession session = request.getSession();
            String cek = null;
        
            Calendar cal = Calendar.getInstance();
            String DATE_FORMAT_NOW = "yyyy-MM-dd";
            SimpleDateFormat sdf = new SimpleDateFormat(DATE_FORMAT_NOW);
            
            FileTA fileTA = new FileTA();
            User user = new User();
            
            String idUser = (String) session.getAttribute("id_user");
            String tglFile = sdf.format(cal.getTime());
            String pesan = null;
            String namaFile = null;
                       
            try {
            PrintWriter out = response.getWriter();
           
            // Check that we have a file upload request
        
            boolean isMultipart = ServletFileUpload.isMultipartContent(request);

            // Create a factory for disk-based file items  
            DiskFileItemFactory factory = new DiskFileItemFactory();  

            // Create a new file upload handler  
            ServletFileUpload fileUpload = new ServletFileUpload(factory);  

            // Parse the request 
            List items = fileUpload.parseRequest(request);
            Iterator ir = items.iterator();

                    while (ir.hasNext()) {
                        FileItem item = (FileItem)ir.next();

                           if (!item.isFormField()) {
                                String lokasiFile = "C:"+File.separator+"File"+File.separator+"TA"+File.separator+item.getName();
                                File file = new File(lokasiFile);
                                item.write(file);
                                namaFile = item.getName();
                                
                                fileTA.setNamaFile(namaFile);
                                fileTA.setLokasiFile(lokasiFile);
                                System.out.println(item.getContentType());
                                
                           }     
                    }
                } catch (FileUploadException ex) {
                    System.out.println(ex.getMessage());
                } catch(IllegalStateException ex){
                    System.out.println(ex.getMessage());
                } catch (Exception ex) {
                    System.out.println(ex.getMessage());
                }
            
            user.setIdUser(idUser);
            fileTA.setUser(user);
            fileTA.setTglFile(tglFile);
            
            if(fileTA.getNamaFile() != null){
                FileTAModel upload = new FileTAModel();
                boolean UploadFile = upload.UploadFile(fileTA);
                if(UploadFile){
                    pesan = "sukses upload";
                }else{
                    pesan = "gagal upload";
                }
                
            }
            //System.out.println(pesan);
            //System.out.println(namaFile);
                          
        return "FileTAController?page=kelolaFileTA&&pesan="+pesan+"&&namaFile="+namaFile;
    }
    
    public String DownloadFileTA() throws FileNotFoundException, IOException{
        
        String namaFile = request.getParameter("file");
        response.setContentType("application/octet-stream");
        response.setHeader("Content-Disposition","attachment;filename="+namaFile);    
        
        File file = new File("C:\\File\\TA\\"+namaFile);
        if(file.canRead()){
        FileInputStream fileIn = new FileInputStream(file);
        ServletOutputStream out = response.getOutputStream();

        byte[] outputByte = new byte[4096];
        //copy binary contect to output stream
        while(fileIn.read(outputByte, 0, 4096) != -1)
        {
                out.write(outputByte, 0, 4096);
        }
        fileIn.close();
        out.flush();
        out.close();
        }else{
            System.out.println("gagal");
        }
        
        return "FileTAController?page=kelolaFileTA";
    }
    
    public String DeleteFileTA(){
        
        String idFile = request.getParameter("idFile");
        String namaFile = request.getParameter("file");
        String pesan = null;
        FileTAModel file = new FileTAModel();        
        int idfile = Integer.parseInt(idFile); 
        boolean DeleteFile = file.DeleteFile(idfile);
        
        if(DeleteFile){
            pesan = "sukses hapus";
        }else{
            pesan = "gagal hapus";
        }
        
        return "FileTAController?page=kelolaFileTA&&pesan="+pesan+"&&namaFile="+namaFile;
    }
}


